package com.ruoyi.web.core;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.ruoyi.common.enums.BusinessErrorEnum;
import com.ruoyi.common.exception.ServiceException;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.log4j.Log4j2;

import java.util.concurrent.CompletableFuture;

/**
 * 发送短信
 *
 * @author Jyl
 */
@Log4j2
public class SendSms
{

    /**
     * 发送验证码构造器
     */
    public SendSms buildSendCaptcha(String phoneNumbers, String code)
    {
        JSONObject smsJson = new JSONObject();
        smsJson.put("code", code);

        this.smsCode = SMS_CODE_CAPTCHA;
        this.phoneNumbers = phoneNumbers;
        this.smsJson = smsJson.toJSONString();
        return this;
    }

    /**
     * 发送群发短信
     */
    public SendSms buildSendSms(String phoneNumbers, String name, String age)
    {
        //尊敬的${name}您好，今天是您${age}岁的生日，祝福您生日快乐
        JSONObject smsJson = new JSONObject();
        smsJson.put("name", name);
        smsJson.put("age", age);

        this.smsCode = SMS_CODE;
        this.phoneNumbers = phoneNumbers;
        this.smsJson = smsJson.toJSONString();
        return this;
    }

    /**
     * 发送群发短信
     */
    public SendSms buildSendSmsD(String phoneNumbers, String name, String festival, String greeting)
    {
        //尊敬的${name}您好，今天是您${age}岁的生日，祝福您生日快乐
        JSONObject smsJson = new JSONObject();
        smsJson.put("name", name);
        smsJson.put("festival", festival);
        smsJson.put("greeting", greeting);

        this.smsCode = SMS_CODE_D;
        this.phoneNumbers = phoneNumbers;
        this.smsJson = smsJson.toJSONString();
        return this;
    }

    /**
     * 读取环境变量 ，短信服务秘钥
     */
    private String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    /**
     * 短息你服务配置模板标识,
     */
    final private String SMS_CODE_CAPTCHA = "SMS_305571154";//验证码标识
    final private String SMS_CODE = "SMS_474660312";//群发短信标识
    //尊敬的 ${name}，临近${festival}，祝您 ${greeting}！
    final private String SMS_CODE_D = "SMS_474815055";//短信模板群发祝福
    final private String signName = "河南聚帮生物药业有限公司";
    /**
     * 发送信息
     */
    public String phoneNumbers;
    public String smsJson;
    public String smsCode;

    /**
     * 发送代码块
     */
    public void send() throws Exception
    {

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and
                // ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(ACCESS_KEY_ID).accessKeySecret(ACCESS_KEY_SECRET)
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder().region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient
                // (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                ).build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumbers)
                .signName(signName)
                .templateCode(smsCode)
                .templateParam(smsJson)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

        // Synchronously get the return value of the API request
        SendSmsResponse resp = response.get();
        JSONObject jsonObject = JSONObject.parseObject(new Gson().toJson(resp));
        log.info("[{}]:{}", "sms sending return message", jsonObject.toJSONString());
        JSONObject body = jsonObject.getJSONObject("body");
        if ("账户余额不足".equals(body.getString("message")))
        {
            throw new ServiceException(BusinessErrorEnum.SMSARREARSOFFEES);
        }
        if ("触发小时级流控Permits:5".equals(body.getString("message")))
        {
            throw new ServiceException(BusinessErrorEnum.TRANSMITFREQUENCY);
        }

        // Asynchronous processing of return values
        /*response.thenAccept(resp ->
        {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable ->
        { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();
    }

    public String getPhoneNumbers()
    {
        return phoneNumbers;
    }

    public void setPhoneNumbers(String phoneNumbers)
    {
        this.phoneNumbers = phoneNumbers;
    }

    public String getSmsJson()
    {
        return smsJson;
    }

    public void setSmsJson(String smsJson)
    {
        this.smsJson = smsJson;
    }

    public String getSmsCode()
    {
        return smsCode;
    }

    public void setSmsCode(String smsCode)
    {
        this.smsCode = smsCode;
    }

    public static void main(String[] args) throws Exception
    {
//        new SendSms()
//                .buildSendCaptcha("18613716647", "1234")
//                .send();
//        new SendSms()
//                .buildSendSms("18613716647", "李四", "21")
//                .send();
        new SendSms()
                .buildSendSmsD("18613716647", "李四", "春节", "身体健康")
                .send();
    }

}
